using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Linear_Light
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Texture2D lightBox;

        KeyboardState currentKeyState;
        KeyboardState lastKeyState;

        string gameState = "SETUP"; //SETUP - PLAY
        int setupStage = 0;
        string setupText = "";
        bool keyReset = false;

        SpriteFont nova35;
        SpriteFont nova20;

        Keys rKey = Keys.Left;
        Keys gKey = Keys.Up;
        Keys bKey = Keys.Right;

        Vector3 red = new Vector3(255, 0, 0);
        Vector3 green = new Vector3(0, 255, 0);
        Vector3 blue = new Vector3(0, 0, 255);
        Vector3 inputRGB = Vector3.Zero;

        int score = 0;
        int highScore = 0;
        Vector2 scoreSizes = Vector2.Zero;

        struct IncomingLight
        {
            internal Vector3 color;
            internal float position;
            internal bool isActive;
        }
        IncomingLight[] incomingLight = new IncomingLight[11];
        int waveSpeed = 0;
        float waveInterval = 0;

        Random randomNum = new Random();

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            graphics.PreferredBackBufferWidth = 1000;
            graphics.PreferredBackBufferHeight = 100;
        }

        protected override void Initialize()
        {
            for (int i = 0; i < 11; i++)
            {
                incomingLight[i].color = Vector3.Zero;
                incomingLight[i].position = graphics.PreferredBackBufferWidth;
                incomingLight[i].isActive = false;
            }

            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);

            lightBox = Content.Load<Texture2D>("Light Box");
            nova35 = Content.Load<SpriteFont>("nova35");
            nova20 = Content.Load<SpriteFont>("nova20");
        }

        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        protected override void Update(GameTime gameTime)
        {
            currentKeyState = Keyboard.GetState();

            //check for esc key exit
            if (IsKeyPressed(Keys.Escape, "PRESS"))
                this.Exit();

            #region input
            //reset color before checking what lights to mix together
            inputRGB = Vector3.Zero;

            if (IsKeyPressed(rKey, "HOLD"))
                inputRGB += red;

            if (IsKeyPressed(gKey, "HOLD"))
                inputRGB += green;

            if (IsKeyPressed(bKey, "HOLD"))
                inputRGB += blue;
            #endregion

            if (gameState == "SETUP")
            {
                #region setup code
                switch (setupStage)
                {
                    case 0:
                        if (!keyReset)
                            setupText = "Press the Left Arrow Key. It turns your Light Wave red.";
                        else
                            setupText = "O.K. Let's go over the new control setting.\nPress the Left Ctrl Key. It turns your Light Wave red.";

                        if (inputRGB == new Vector3(255, 0, 0))
                            setupStage++;
                        break;
                    case 1:
                        if (!keyReset)
                            setupText = "Now press the Up Arrow Key. It turns your Light Wave green.";
                        else
                            setupText = "Now press the Left Shift Key. It turns your Light Wave green.";

                        if (inputRGB == new Vector3(0, 255, 0))
                            setupStage++;
                        break;
                    case 2:
                        if (!keyReset)
                            setupText = "Finally, press the Right Arrow Key. It turns your Light Wave blue.";
                        else
                            setupText = "Finally, press the Z Key. It turns your Light Wave blue.";

                        if (inputRGB == new Vector3(0, 0, 255))
                            setupStage++;
                        break;
                    case 3:
                        if (!keyReset)
                            setupText = "O.K. Now for a Light Wave Combination.\nPress both the Left and Up Arrow Keys together. It turns your Light Wave yellow.";
                        else
                            setupText = "O.K. Now for a Light Wave Combination.\nPress both the Left Ctrl and Left Shift Keys together. It turns your Light Wave yellow.";

                        if (inputRGB == new Vector3(255, 255, 0))
                            setupStage++;
                        break;
                    case 4:
                        if (!keyReset)
                            setupText = "Next, press the Up and Right Arrow Keys together. It turns your Light Wave cyan.";
                        else
                            setupText = "Next, press the Left Shift and Z Keys together. It turns your Light Wave cyan.";

                        if (inputRGB == new Vector3(0, 255, 255))
                            setupStage++;
                        break;
                    case 5:
                        if (!keyReset)
                            setupText = "Now, press the Left and Right Arrow Keys together. It turns your Light Wave magenta.";
                        else
                            setupText = "Now, press the Left Ctrl and Z Keys together. It turns your Light Wave magenta.";

                        if (inputRGB == new Vector3(255, 0, 255))
                            setupStage++;
                        break;
                    case 6:
                        if (!keyReset)
                            setupText = "Finally, press all three Arrow Keys together. It turns your Light Wave white.\n" +
                                "This won't work on some keyboards. If you can't get white, please press Enter.";
                        else
                            setupText = "Finally, press all three keys together. (Left Ctrl, Left Shift, and Z)\nIt turns your Light Wave white.";

                        if (inputRGB == new Vector3(255, 255, 255))
                            setupStage++;
                        if (IsKeyPressed(Keys.Enter, "PRESS"))
                        {
                            //reset keys for other keyboards
                            rKey = Keys.LeftControl;
                            gKey = Keys.LeftShift;
                            bKey = Keys.Z;
                            keyReset = true;
                            setupStage = 0;
                        }
                        break;
                    case 7:
                        setupText = "The object is to match the color of Light Waves that approach from the right.\n" +
                            "If you miss one, your score will be reset to zero. Press Enter to start playing. Good Luck!";

                        if (IsKeyPressed(Keys.Enter, "PRESS"))
                            gameState = "PLAY";
                        break;
                }
                #endregion
            }
            else if (gameState == "PLAY")
            {
                #region incoming light randomization and updates
                waveSpeed = 100 + (score * 10);

                for (int i = 0; i < 10; i++)
                {
                    if (!incomingLight[i].isActive && waveInterval == 0)
                    {
                        //set up a new light wave
                        incomingLight[i].isActive = true;

                        //put a number into waveInterval so the other waves arent instant
                        waveInterval = randomNum.Next(1, 4);

                        while (incomingLight[i].color == Vector3.Zero)
                        {
                            //randomly add colors to this light wave
                            if (randomNum.Next(0, 2) == 1)
                                incomingLight[i].color += red;

                            if (randomNum.Next(0, 2) == 1)
                                incomingLight[i].color += green;

                            if (randomNum.Next(0, 2) == 1)
                                incomingLight[i].color += blue;
                        }
                    }
                    else if (incomingLight[i].isActive)
                    {
                        //update light waves position based on speed and gameTime
                        incomingLight[i].position = MathHelper.Clamp((float)(incomingLight[i].position - (waveSpeed * gameTime.ElapsedGameTime.TotalSeconds)), 0, graphics.PreferredBackBufferWidth);

                        //wave has hit the left edge
                        if (incomingLight[i].position == 0)
                        {
                            //check to see if this wave matches input
                            if (incomingLight[i].color == inputRGB)
                            {
                                score++;
                            }
                            else
                            {
                                score = 0;
                            }

                            //reset this wave by moving all other waves up one
                            for (int x = 0; x < 10; x++)
                            {
                                incomingLight[x].color = incomingLight[x + 1].color;
                                incomingLight[x].position = incomingLight[x + 1].position;
                                incomingLight[x].isActive = incomingLight[x + 1].isActive;
                            }
                        }
                    }
                }

                //take away from waveInterval
                waveInterval = MathHelper.Clamp((float)(waveInterval - gameTime.ElapsedGameTime.TotalSeconds), 0, 100);
                #endregion

                if (score > highScore)
                    highScore = score;
            }

            lastKeyState = currentKeyState;
            base.Update(gameTime);
        }


        bool IsKeyPressed(Keys key, string pressOrHold)
        {
            if (IsActive) // <-- prevent key click registration while the application isnt the active window
            {
                //checks to see what kind of check to perform
                if (pressOrHold == "PRESS")
                {
                    //for checking things that should only be pressed once
                    return (currentKeyState.IsKeyDown(key) && lastKeyState.IsKeyUp(key));
                }
                else if (pressOrHold == "HOLD")
                {
                    //for checking things that can be held down (movement)
                    return (currentKeyState.IsKeyDown(key));
                }
                else
                {
                    //we found a bad calling statement. return false so nothing adverse happens.
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        protected override void Draw(GameTime gameTime)
        {
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied);
            GraphicsDevice.Clear(Color.Transparent);

            if (gameState == "SETUP")
            {
                DrawSetupScreen(gameTime, spriteBatch);
            }
            else if (gameState == "PLAY")
            {
                DrawPlayScreen(gameTime, spriteBatch);
            }

            spriteBatch.End();

            base.Draw(gameTime);
        }

        void DrawSetupScreen(GameTime gameTime, SpriteBatch spriteBatch)
        {
            spriteBatch.DrawString(nova20, setupText, new Vector2(20, graphics.PreferredBackBufferHeight / 2 - 50), Color.DarkGray);

            //draw input color wave
            spriteBatch.Draw(lightBox, new Rectangle(0, 0, 10, graphics.PreferredBackBufferHeight), new Color(inputRGB));
        }

        void DrawPlayScreen(GameTime gameTime, SpriteBatch spriteBatch)
        {
            //draw incoming light waves
            for (int i = 0; i < 10; i++)
            {
                if (incomingLight[i].isActive) //only draw active waves
                    spriteBatch.Draw(lightBox, new Rectangle((int)incomingLight[i].position, 0, 10, graphics.PreferredBackBufferHeight), new Color(incomingLight[i].color));
            }

            //draw input color wave
            spriteBatch.Draw(lightBox, new Rectangle(0, 0, 10, graphics.PreferredBackBufferHeight), new Color(inputRGB));

            //draw score and high score
            scoreSizes = nova35.MeasureString("" + score);
            spriteBatch.DrawString(nova35, "" + score, new Vector2(graphics.PreferredBackBufferWidth / 2 - scoreSizes.X / 2, graphics.PreferredBackBufferHeight / 2 - scoreSizes.Y / 2 - 25), Color.DarkGray);
            scoreSizes = nova35.MeasureString("" + highScore);
            spriteBatch.DrawString(nova35, "" + highScore, new Vector2(graphics.PreferredBackBufferWidth / 2 - scoreSizes.X / 2, graphics.PreferredBackBufferHeight / 2 - scoreSizes.Y / 2 + 25), Color.DarkGray);
        }
    }
}
